package middleware

import (
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
	"syuee.com/iShot/common"
	"syuee.com/iShot/model"
	"syuee.com/iShot/response"
)

func AuthMiddleware() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		//获取authorization hander
		var tokenString string
		xtokenString := ctx.GetHeader("X-Auth-Token")
		atokenString := ctx.GetHeader("Authorization")
		//fmt.Println(tokenString)

		//validate token format
		if xtokenString != "" {
			tokenString = xtokenString
		} else if atokenString != "" && !strings.HasPrefix(tokenString, "Bearer ") {
			tokenString = atokenString[7:]
		} else {
			response.Response(ctx, http.StatusUnauthorized, nil, 401, "权限不足")
			ctx.Abort()
			return
		}
		//解析token
		token, claims, err := common.ParseToken(tokenString)
		if err != nil || !token.Valid {
			response.Response(ctx, http.StatusUnauthorized, nil, 401, "权限不足")
			ctx.Abort()
			return
		}
		//验证通过后获取claim中的userID
		userId := claims.UserId
		DB := common.GetDB()
		var user model.I_manager

		DB.First(&user, userId)

		//用户
		if user.Mg_id == 0 {
			response.Response(ctx, http.StatusUnauthorized, nil, 401, "权限不足")
			ctx.Abort()
			return
		}

		//用户存在 将user 的信息写入上下文
		ctx.Set("user", user)

		ctx.Next()
	}
}
